const canvas = document.getElementById('webgl')
const gl = getWebGLContext(canvas)

let VertexShaderSource =
    'attribute vec4 a_Position;\n' +
    'attribute float a_PointSize;\n'+
    'void main(){ \n' +
    '   gl_Position = a_Position;\n' +
    '   gl_PointSize = a_PointSize;\n' +
    '}\n'
let FragmentShaderSource =
    'void main(){\n' +
    '    gl_FragColor = vec4(0.0,1.0,0.0,1.0);\n' +
    '}\n'

function main() {
    initShaders(gl, VertexShaderSource, FragmentShaderSource)
    let a_Position = gl.getAttribLocation(gl.program, 'a_Position')
    let a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize')

    if (a_Position < 0) {
        console.log('Failed to get the storage location of a_Position')
        return
    }

    canvas.onmousedown = (e) => {
        click(e, gl, canvas, a_Position)
    }
    gl.clearColor(0, 0, 0, 1)
    gl.clear(gl.COLOR_BUFFER_BIT)
    gl.vertexAttrib1f(a_PointSize, 5.0)
}


let g_points = []
function click(e, gl, canvas, a_Position) {
    let x = e.clientX
    let y = e.clientY
    let rect = e.target.getBoundingClientRect()
    x = ((x - rect.left) - canvas.height / 2) / (canvas.height / 2)
    y = (canvas.width / 2 - (y - rect.top)) / (canvas.width / 2)
    g_points.push(x)
    g_points.push(y)

    gl.clear(gl.COLOR_BUFFER_BIT)

    let len = g_points.length
    for (let i = 0; i < len; i += 2) {
        gl.vertexAttrib3f(a_Position, g_points[i], g_points[i + 1], 0.0)
        gl.drawArrays(gl.POINTS, 0, 1)
    }
}